package com.wang.hello;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

/**
 * @Author 97089
 * @Date 2022/1/4 10:43
 * @Version 1.0
 */
public class AppClientHello {

    //远程的主机IP
    private final String host;

    //远程主机的端口
    private final int port;

    public AppClientHello(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup loopGroup = new NioEventLoopGroup();
        try{
            Bootstrap bs = new Bootstrap();
            bs.group(loopGroup)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(host,port))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //自定义的Handler
                            ch.pipeline().addLast(new HandlerClientHello());
                        }
                    });

            //链接到远程节点，等待链接完成
            ChannelFuture future = bs.connect().sync();

            //发送消息到服务器
            future.channel().writeAndFlush(Unpooled.copiedBuffer("HelloWorld", CharsetUtil.UTF_8));

            //阻塞操作，closeFuture（）开启一个channel的监听器
            future.channel().closeFuture().sync();
        }finally {
            //优雅关闭
            loopGroup.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws Exception {
        new AppClientHello("127.0.0.1",8081).run();
    }
}
